const Redis = require("ioredis")
const { Store } = require("koa-session2")
const { redis } = require('../config/config')

class RedisStore extends Store {
    constructor() {
        super()
        this.redis = new Redis({
            host: redis.host,
            password: redis.password
        })
        this.maxAge = redis.maxAge
    }

    async get(sid, ctx) {
        let data = await this.redis.get(`SESSION:${sid}`)
        await this.redis.expire(`SESSION:${sid}`, this.maxAge)
        return JSON.parse(data)
    }

    async set(session, { sid = this.getID(24), maxAge = this.maxAge } = {}, ctx) {
        try {
            // Use redis set EX to automatically drop expired sessions
            await this.redis.set(`SESSION:${sid}`, JSON.stringify(session), 'EX', maxAge)
        } catch (e) {}
        return sid;
    }

    async destroy(sid, ctx) {
        return await this.redis.del(`SESSION:${sid}`)
    }
}

module.exports = RedisStore